<template>
  <div class="notifications-container">
    <el-card class="notifications-card">
      <template #header>
        <div class="card-header">
          <h2>通知中心</h2>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="markAllAsRead" :disabled="!unreadNotifications.length">
              全部标为已读
            </el-button>
            <el-button type="danger" size="small" @click="clearAllNotifications" :disabled="!notifications.length">
              清空通知
            </el-button>
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部通知" name="all">
          <div v-if="notifications.length === 0" class="empty-state">
            <el-empty description="暂无通知" />
          </div>
          <notification-list 
            v-else 
            :notifications="notifications" 
            @mark-read="markAsRead" 
            @delete="deleteNotification"
          />
        </el-tab-pane>
        <el-tab-pane label="未读通知" name="unread">
          <div v-if="unreadNotifications.length === 0" class="empty-state">
            <el-empty description="暂无未读通知" />
          </div>
          <notification-list 
            v-else 
            :notifications="unreadNotifications" 
            @mark-read="markAsRead" 
            @delete="deleteNotification"
          />
        </el-tab-pane>
      </el-tabs>
      
      <div class="pagination-container" v-if="totalPages > 1">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalItems"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, Document, Share, Message, Camera } from '@element-plus/icons-vue'
import axios from 'axios'

// 通知列表组件
const NotificationList = {
  props: {
    notifications: {
      type: Array,
      required: true
    }
  },
  emits: ['mark-read', 'delete'],
  template: `
    <div class="notification-list">
      <div v-for="notification in notifications" :key="notification.id" 
           class="notification-item" :class="{ 'unread': !notification.read }">
        <div class="notification-content">
          <div class="notification-icon">
            <el-icon v-if="notification.type === 'system'"><Bell /></el-icon>
            <el-icon v-else-if="notification.type === 'document'"><Document /></el-icon>
            <el-icon v-else-if="notification.type === 'share'"><Share /></el-icon>
            <el-icon v-else><Message /></el-icon>
          </div>
          <div class="notification-body">
            <div class="notification-title">{{ notification.title }}</div>
            <div class="notification-message">{{ notification.message }}</div>
            <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
          </div>
        </div>
        <div class="notification-actions">
          <el-button v-if="!notification.read" type="text" @click="$emit('mark-read', notification.id)">
            标为已读
          </el-button>
          <el-button type="text" @click="$emit('delete', notification.id)">
            删除
          </el-button>
        </div>
      </div>
    </div>
  `,
  components: {
    Bell,
    Document,
    Share,
    Message
  },
  methods: {
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString();
    }
  }
}

export default {
  name: 'Notifications',
  components: {
    NotificationList,
    Bell,
    Document,
    Share,
    Message,
    Camera
  },
  setup() {
    const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
    const notifications = ref([]);
    const activeTab = ref('all');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const loading = ref(false);

    // 模拟通知数据
    const mockNotifications = [
      {
        id: 1,
        title: '系统通知',
        message: '欢迎使用文档管理系统',
        type: 'system',
        read: false,
        created_at: new Date(Date.now() - 3600000).toISOString()
      },
      {
        id: 2,
        title: '文档更新',
        message: '您的文档"项目计划书"已更新',
        type: 'document',
        read: false,
        created_at: new Date(Date.now() - 7200000).toISOString()
      },
      {
        id: 3,
        title: '分享通知',
        message: '用户张三与您分享了文档"会议记录"',
        type: 'share',
        read: true,
        created_at: new Date(Date.now() - 86400000).toISOString()
      }
    ];

    const unreadNotifications = computed(() => {
      return notifications.value.filter(notification => !notification.read);
    });

    const totalPages = computed(() => {
      return Math.ceil(totalItems.value / pageSize.value);
    });

    const fetchNotifications = async () => {
      try {
        loading.value = true;
        
        // 使用模拟数据代替API调用
        setTimeout(() => {
          // 根据当前标签页过滤数据
          let filteredNotifications = [...mockNotifications];
          if (activeTab.value === 'unread') {
            filteredNotifications = filteredNotifications.filter(n => !n.read);
          }
          
          // 模拟分页
          const startIndex = (currentPage.value - 1) * pageSize.value;
          const endIndex = startIndex + pageSize.value;
          notifications.value = filteredNotifications.slice(startIndex, endIndex);
          totalItems.value = filteredNotifications.length;
          
          loading.value = false;
        }, 500);
        
      } catch (error) {
        console.error('获取通知失败:', error);
        ElMessage.error('获取通知失败，请稍后重试');
        loading.value = false;
      }
    };

    const markAsRead = async (notificationId) => {
      try {
        // 模拟API调用
        setTimeout(() => {
          // 更新本地状态
          const index = notifications.value.findIndex(n => n.id === notificationId);
          if (index !== -1) {
            notifications.value[index].read = true;
          }
          
          // 同时更新模拟数据源
          const mockIndex = mockNotifications.findIndex(n => n.id === notificationId);
          if (mockIndex !== -1) {
            mockNotifications[mockIndex].read = true;
          }
          
          ElMessage.success('已标记为已读');
        }, 300);
      } catch (error) {
        console.error('标记已读失败:', error);
        ElMessage.error('操作失败，请稍后重试');
      }
    };

    const markAllAsRead = async () => {
      try {
        // 模拟API调用
        setTimeout(() => {
          // 更新所有未读通知为已读
          notifications.value.forEach(notification => {
            notification.read = true;
          });
          
          // 同时更新模拟数据源
          mockNotifications.forEach(notification => {
            notification.read = true;
          });
          
          ElMessage.success('已将所有通知标记为已读');
        }, 300);
      } catch (error) {
        console.error('标记全部已读失败:', error);
        ElMessage.error('操作失败，请稍后重试');
      }
    };

    const deleteNotification = async (notificationId) => {
      try {
        // 模拟API调用
        setTimeout(() => {
          // 从本地状态中删除
          notifications.value = notifications.value.filter(n => n.id !== notificationId);
          
          // 从模拟数据源中删除
          const index = mockNotifications.findIndex(n => n.id === notificationId);
          if (index !== -1) {
            mockNotifications.splice(index, 1);
            totalItems.value--;
          }
          
          ElMessage.success('通知已删除');
        }, 300);
      } catch (error) {
        console.error('删除通知失败:', error);
        ElMessage.error('操作失败，请稍后重试');
      }
    };

    const clearAllNotifications = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要清空所有通知吗？此操作不可恢复。',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        // 模拟API调用
        setTimeout(() => {
          // 清空本地状态
          notifications.value = [];
          
          // 清空模拟数据源
          mockNotifications.length = 0;
          totalItems.value = 0;
          
          ElMessage.success('已清空所有通知');
        }, 300);
      } catch (error) {
        if (error !== 'cancel') {
          console.error('清空通知失败:', error);
          ElMessage.error('操作失败，请稍后重试');
        }
      }
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchNotifications();
    };

    // 监听标签页变化
    const handleTabChange = () => {
      currentPage.value = 1; // 切换标签页时重置为第一页
      fetchNotifications();
    };

    onMounted(() => {
      fetchNotifications();
    });

    return {
      notifications,
      unreadNotifications,
      activeTab,
      currentPage,
      totalItems,
      pageSize,
      totalPages,
      loading,
      fetchNotifications,
      markAsRead,
      markAllAsRead,
      deleteNotification,
      clearAllNotifications,
      handlePageChange
    };
  }
}
</script>

<style scoped>
.notifications-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.notifications-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.notification-list {
  margin-top: 10px;
}

.notification-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #ecf5ff;
}

.notification-content {
  display: flex;
  align-items: flex-start;
  flex: 1;
}

.notification-icon {
  margin-right: 15px;
  font-size: 20px;
  color: #409eff;
}

.notification-body {
  flex: 1;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-message {
  color: #606266;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 